//
//  WAFlickrManager.m
//  WeatherApp
//
//  Created by Yuliya Grasevych on 24.07.14.
//  Copyright (c) 2014 Yuliya Grasevych. All rights reserved.
//

#import "WAFlickrManager.h"
#import <ObjectiveFlickr/ObjectiveFlickr.h>
#import "SampleAPIKey.h"

typedef void (^FlickrCompletionBlock)(NSImage *image);

static OFFlickrAPIContext *_flickrContext = nil;
static NSMutableDictionary *_requests = nil;

@interface WAFlickrManager () <OFFlickrAPIRequestDelegate>

+(NSMutableDictionary *)requests;

@property (nonatomic) OFFlickrAPIRequest *flickrRequest;
@property (nonatomic, copy) FlickrCompletionBlock completionHandler;
@property (nonatomic) WALocation *location;
@property (nonatomic) NSArray *tags;
@property (nonatomic) CGFloat coordinateDelta;
@end

@implementation WAFlickrManager

-(id)init
{
    self = [super init];
    if (self) {
        
        _coordinateDelta = 0.5;
    }
    return self;
}
+(void)getWeatherBackgroundByTags:(NSArray *)tags forLocation:(WALocation *)location completion:(void (^)(NSImage *))completion
{
    WAFlickrManager *manager = [[WAFlickrManager alloc] init];
    OFFlickrAPIRequest *flickrRequest = [[OFFlickrAPIRequest alloc] initWithAPIContext:[self flickrContext]];
    manager.flickrRequest = flickrRequest;
    [flickrRequest setDelegate:manager];
    [[self requests] setObject:manager forKey:manager.description];
    manager.completionHandler = completion;
    manager.location = location;
    manager.tags = tags;
    
    NSDictionary *params = @{ @"api_key": OBJECTIVE_FLICKR_SAMPLE_API_KEY,
                              @"tags": [manager.tags componentsJoinedByString:@","],
                              @"tag_mode": @"AND",
                              @"privacy_filter": @"1",
                              @"per_page": @"50",
                              @"content_type": @"1", // photos only
                              @"woe_id": manager.location.woeid,
                              @"lat": [NSString stringWithFormat:@"%f", manager.location.location.coordinate.latitude],
                              @"lon": [NSString stringWithFormat:@"%f", manager.location.location.coordinate.longitude],
                              @"accuracy": @"14", // city ~ street
                              @"group_id": @"1463451@N25",
                              @"sort": @"relevance" };
    
    [flickrRequest callAPIMethodWithGET:@"flickr.photos.search" arguments:params];
	
}

+(OFFlickrAPIContext *)flickrContext
{
    if (!_flickrContext) {
        
        _flickrContext = [[OFFlickrAPIContext alloc] initWithAPIKey:OBJECTIVE_FLICKR_SAMPLE_API_KEY sharedSecret:OBJECTIVE_FLICKR_SAMPLE_API_SHARED_SECRET];
    }
    return _flickrContext;
}
+(NSMutableDictionary *)requests
{
    if (!_requests) {
        
        _requests = [NSMutableDictionary dictionaryWithCapacity:1];
    }
    return _requests;
}

#pragma mark - Flickr Delegate
-(void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary
{
    NSDictionary *photoDict = nil;
    NSArray *photosArray = [inResponseDictionary valueForKeyPath:@"photos.photo"];
    NSInteger dictIndex = MIN(photosArray.count-1, fmod([NSDate timeIntervalSinceReferenceDate],50));
    
    if (dictIndex > -1) {
        
        photoDict = [photosArray objectAtIndex:dictIndex];
    }
    if (!photoDict) {
        
        NSString *bbox = [NSString stringWithFormat:@"%f,%f,%f,%f",
                          self.location.location.coordinate.longitude-self.coordinateDelta,
                          self.location.location.coordinate.latitude-self.coordinateDelta,
                          self.location.location.coordinate.longitude+self.coordinateDelta,
                          self.location.location.coordinate.latitude+self.coordinateDelta];
        self.coordinateDelta += 0.5;
        
        NSDictionary *params = @{ @"api_key": OBJECTIVE_FLICKR_SAMPLE_API_KEY,
                                  @"tags": [self.tags componentsJoinedByString:@","],
                                  @"tag_mode": @"AND",
                                  @"privacy_filter": @"1",
                                  @"per_page": @"50",
                                  @"content_type": @"1", // photos only
                                  @"woe_id": self.location.woeid,
                                  @"bbox": bbox,
                                  @"accuracy": @"14", // city ~ street
                                  @"group_id": @"1463451@N25",
                                  @"sort": @"relevance" };
        
        [inRequest callAPIMethodWithGET:@"flickr.photos.search" arguments:params];
        return;
    }
		
    self.coordinateDelta = 0.5;
	NSURL *photoURL = [[WAFlickrManager flickrContext] photoSourceURLFromDictionary:photoDict size:OFFlickrLargeSize];
    NSURLRequest *photoRequest = [NSURLRequest requestWithURL:photoURL];
    [NSURLConnection sendAsynchronousRequest:photoRequest
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               
                               if (!connectionError) {
                               
                                   NSImage *photo = [[NSImage alloc] initWithData:data];
                                   
                                   self.completionHandler(photo);
                                   [[WAFlickrManager requests] removeObjectForKey:self.description];
                               }
                           }];
}
-(void)dealloc
{
    
}
-(void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didFailWithError:(NSError *)inError
{
    
}
@end
